<template>
    <div class="bg-white p-3 rounded-lg shadow relative">
        <div class="relative">
            <video ref="videoRef" controls class="w-full rounded" @click="toggleLoopPlay"></video>
            <!-- 循环播放控制按钮 -->
            <button @click="toggleLoopPlay"
                class="absolute bottom-2 right-2 bg-black bg-opacity-50 text-white px-2 py-1 z-4 rounded">
                {{ isLooping ? '停止循环' : '循环播放' }}
            </button>
            <!-- 添加截图区域指示框 -->
            <div v-if="store.videoFile && store.videoDimensions.width > 0"
                class="absolute top-0 left-0 pointer-events-none" :style="{
                width: `${videoElement?.offsetWidth || 0}px`,
                height: `${videoElement?.offsetHeight || 0}px`
            }">
                <!-- 截图区域虚线框 -->
                <div class="absolute border-2 border-dashed border-[#00ff00]" :style="{
                left: `${store.cropParams.left * (videoElement?.offsetWidth / store.videoDimensions.width) || 0}px`,
                top: `${store.cropParams.top * (videoElement?.offsetHeight / store.videoDimensions.height) || 0}px`,
                width: `${store.cropParams.width * (videoElement?.offsetWidth / store.videoDimensions.width) || 0}px`,
                height: `${store.cropParams.height * (videoElement?.offsetHeight / store.videoDimensions.height) || 0}px`
            }">
                    <!-- 截图参数显示 -->
                    <div
                        class="absolute -top-6 left-0 bg-black bg-opacity-70 text-white text-xs px-2 py-1 rounded whitespace-nowrap">
                        {{ store.cropParams.left }}, {{ store.cropParams.top }}, {{ store.cropParams.width }},
                        {{ store.cropParams.height }}
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue';
import { useVideoStore } from '../stores/videoStore';

// 使用 Pinia store
const store = useVideoStore();

// 本地状态
const videoRef = ref(null);
const videoElement = ref(null);
const isLooping = ref(false);

// 循环播放控制
const toggleLoopPlay = () => {
    console.log('toggleLoopPlay', isLooping.value);
    if (!videoElement.value) {
        console.error('视频元素不存在');
        return;
    }

    isLooping.value = !isLooping.value;
    videoElement.value.loop = false; // 显式禁用原生循环

    if (isLooping.value) {
        videoElement.value.currentTime = store.startTime;
        videoElement.value.play()
            .then(() => console.log('循环播放已启动'))
            .catch(err => {
                console.error('播放失败:', err);
                isLooping.value = false;
            });
    } else {
        videoElement.value.pause();
        videoElement.value.currentTime = store.startTime; // 重置到起点
    }
};

// 监听视频时间更新
const handleTimeUpdate = () => {
    if (!videoElement.value || !isLooping.value) return;

    const currentTime = videoElement.value.currentTime;
    store.currentTime = currentTime;

    const loopStartTime = store.startTime || 0;
    const loopEndTime = store.endTime > 0 ? store.endTime : videoElement.value.duration;

    // 如果当前时间超过或等于结束时间，则回到开始时间
    if (currentTime >= loopEndTime - 0.05) {
        console.log('循环回到开始时间', loopStartTime);
        restartPlayback();
    }
};

watch([() => store.startTime, () => store.endTime], ([newStart, newEnd]) => {
    console.log('时间参数更新:', newStart, newEnd);
    if (isLooping.value) restartPlayback();
})

const restartPlayback = () => {
    videoElement.value.currentTime = loopStartTime;
    if (isLooping.value && videoElement.value.paused) {
        videoElement.value.play().catch(console.error);
    }
}

// 添加视频结束事件监听
const handleVideoEnded = () => {
    if (isLooping.value) {
        console.log('视频结束，重新开始播放');
        videoElement.value.currentTime = store.startTime || 0;
        videoElement.value.play().catch(err => {
            console.error('重新播放失败:', err);
        });
    }
};

onMounted(() => {
    videoElement.value = videoRef.value;
    store.sourceVideo = videoElement.value;

    // 添加视频事件监听
    if (videoElement.value) {
        videoElement.value.addEventListener('timeupdate', handleTimeUpdate);
        videoElement.value.addEventListener('ended', handleVideoEnded);
        videoElement.value.setAttribute('playsinline', '');
        videoElement.value.setAttribute('webkit-playsinline', '');
        videoElement.value.setAttribute('x5-video-player-type', 'h5');
        // 设置循环属性
        videoElement.value.loop = false; // 我们手动控制循环，不使用原生loop
    }

    // 发出更新事件
    emit('update:videoElement', videoElement.value);
});


onUnmounted(() => {
    // 移除事件监听
    if (videoElement.value) {
        videoElement.value.removeEventListener('timeupdate', handleTimeUpdate);
        videoElement.value.removeEventListener('ended', handleVideoEnded);
    }
});

// 定义事件
const emit = defineEmits(['update:videoElement', 'toggle-loop']);
</script>